/*******************************************************************************
 * @note Copyright (C) 2011-2022， Shanghai Panchip Microelectronics Co., Ltd. 
 * @SPDX-License-Identifier: Apache-2.0
 * @history - V0.1, 2022-09-28
*******************************************************************************/
#include <string.h>
#include "userdef.h"
#include "misc.h"


/*
 *  @brief letter char_toupper
 *  @param[in] char byte
 *  @param[out] char byte
 */
char char_toupper(char c) 
{
    if( ( c >= 'a' ) && ( c <= 'z' ) )
        return c + ( 'A' - 'a' );
    return c;
}

void str_toupper(char *str, int len)
{
     /** letter to upper */
    for( int i = 0; i < len; i++ )
    {
        str[i] = char_toupper(str[i]);
    } 
}

/*
 *  C prototype : void StrToHex(byte *pbDest, char *pszSrc, int nLen)
 *  parameter(s): [OUT] pbDest - 输出缓冲区
 *  [IN] pszSrc - 字符串
 *  [IN] nLen - 16进制数的字节数(字符串的长度/2)
 *  return value: success:  0
                 fail:    -1
 *  remarks : 将字符串转化为16进制数
*/
int StrToHex(u8 *pbDest, char *pszSrc, int nLen)
{
    char h1, h2;
    u8 s1, s2;
    
    for (int i = 0; i < nLen; i++)
    {
        h1 = pszSrc[2 * i];
        h2 = pszSrc[2 * i + 1];

        s1 = char_toupper(h1) - 0x30;
        if (s1 > 9) s1 -= 7;

        s2 = char_toupper(h2) - 0x30;
        if (s2 > 9) s2 -= 7;

        if ( s1 > 15 || s2 > 15 )
        {
            return -1;
        }
        
        pbDest[i] = s1 * 16 + s2;
    }

    return 0;
}

/*
 *  C prototype : void HexToStr(char *pszDest, byte *pbSrc, int nLen)
 *  parameter(s): [OUT] pszDest - 存放目标字符串
 *  [IN] pbSrc - 输入16进制数的起始地址
 *  [IN] nLen - 16进制数的字节数
 *  return value:
 *  remarks : 将16进制数转化为字符串
*/
void HexToStr(char *pszDest, u8 *pbSrc, int nLen)
{
    char ddl, ddh;
    for (int i = 0; i < nLen; i++)
    {
        ddh = 48 + pbSrc[i] / 16;
        ddl = 48 + pbSrc[i] % 16;
        if (ddh > 57) ddh = ddh + 7;
        if (ddl > 57) ddl = ddl + 7;
        pszDest[i * 2] = ddh;
        pszDest[i * 2 + 1] = ddl;
    }

    pszDest[nLen * 2] = '\0';
}


